<?php

namespace App\Exports;

use App\Models\Supplier;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Concerns\FromQuery;

class SupplierExport extends BaseExport implements FromQuery
{
    public function headings(): array
    {
        return [
            '编号',
            '供应商名称',
            '所在地区',
            '联系人',
            '手机号',
            '综合评分',
            '销售额',
            '订单数',
            '售后率',
            '状态',
            '创建时间',
        ];
    }

    public function map($row): array
    {
        $row = $row->toArray();
        return [
            $row['id'],
            $row['name'],
            implode('', [$row['province']['name'] ?? '', $row['city']['name'] ?? '', $row['area']['name'] ?? '']),
            $row['contact'],
            $row['phone'],
            '',
            '',
            '',
            '',
            Supplier::STATUS_MAP[$row['status']],
            $row['created_at']
        ];
    }

    /**
     * @return \Illuminate\Database\Query\Builder
     */
    public function query()
    {
        return Supplier::query()
            ->withoutGlobalScope('status')
            ->with([
                'province:code,name',
                'city:code,name',
                'area:code,name',
            ])
            ->when($this->request['name'] ?? '', function (Builder $query, $name) {
                $query->where('name', 'like', '%' . $name . '%');
            })
            ->when($this->request['province'] ?? 0, function (Builder $query, $province) {
                $query->where('province', $province);
            })
            ->when($this->request['city'] ?? 0, function (Builder $query, $city) {
                $query->where('city', $city);
            })
            ->when($this->request['area'] ?? 0, function (Builder $query, $area) {
                $query->where('area', $area);
            })
            ->when($this->request['contact'] ?? '', function (Builder $query, $contact) {
                $query->where('contact', 'like', '%' . $contact . '%');
            })
            ->when($this->request['phone'] ?? '', function (Builder $query, $phone) {
                $query->where('phone', 'like', '%' . $phone . '%');
            })
            ->when($this->request['status'] ?? 0, function (Builder $query, $status) {
                $query->where('status', $status);
            })
            ->when($this->request['created_at_begin'] ?? '', function (Builder $query, $createdAtBegin) {
                $query->where('created_at', '>=', $createdAtBegin);
            })
            ->when($this->request['created_at_end'] ?? '', function (Builder $query, $createdAtEnd) {
                $query->where('created_at', '<=', Carbon::parse($createdAtEnd)->endOfDay());
            })
            ->select(['id', 'name', 'province', 'city', 'area', 'contact', 'phone', 'status', 'created_at']);
    }
}
